//
//  Extension+UINavigationItem.swift
//  ProductBase
//
//  Created by 许必成 on 2020/7/22.
//  Copyright © 2020 东信北邮信息技术有限公司. All rights reserved.
//

import UIKit

extension UINavigationItem {
    
    /**添加有文字和图片的item*/
    func addItem(title: String, imgName: String, target: Any, action: Selector, isLeft: Bool){
        
        let img = UIImage(named: imgName)
        
        let btn = UIButton(type: .custom)
        
        btn.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        btn.setTitleColor(.blue, for: .normal)
        btn.setTitle(title, for: .normal)
        btn.setBackgroundImage(img, for: .normal)
        btn.addTarget(target, action: action, for: .touchUpInside)
        
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        if isLeft{
            self.leftBarButtonItem = barButtonItem
        }else{
            self.rightBarButtonItem = barButtonItem
        }
        
    }
    
    func addItem(title: String, target: Any, action: Selector, isLeft: Bool){
                
        let btn = UIButton(type: .custom)
        
        btn.frame = CGRect(x: 0, y: 0, width: 50, height: 25)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        btn.setTitleColor(.blue, for: .normal)
        btn.setTitle(title, for: .normal)
        btn.addTarget(target, action: action, for: .touchUpInside)
        
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        if isLeft{
            self.leftBarButtonItem = barButtonItem
        }else{
            self.rightBarButtonItem = barButtonItem
        }
        
    }
    
    func addItem(imgName: String, target: Any, action: Selector, isLeft: Bool){
        
        let img = UIImage(named: imgName)
        
        let btn = UIButton(type: .custom)
        
        btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        btn.setImage(img?.withRenderingMode(.alwaysOriginal), for: .normal)
        btn.addTarget(target, action: action, for: .touchUpInside)
        
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        if isLeft{
            self.leftBarButtonItem = barButtonItem
        }else{
            self.rightBarButtonItem = barButtonItem
        }
        
    }
    
    ///添加返回按钮
    func addBackItem(target: Any, action: Selector){
        
        self.addItem(imgName: "back", target: target, action: action, isLeft: true)
    }
    
}
